//
//  BoutiqueViewController.m
//  kr_36
//
//  Created by lmt on 16/1/23.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "BoutiqueViewController.h"
#import "BoutiqueCollectionViewCell.h"
#import "LMTAFNetwork.h"
#import <UIImageView+WebCache.h>
#import "BoutiqueModel.h"
#import "LMTTImeChuo.h"
#import <MJRefresh.h>
#import "BoutiqueDetailController.h"



@interface BoutiqueViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, retain) BoutiqueModel *model;

@end

@implementation BoutiqueViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"精选";
    
    // 创建collectionView
    [self creatCollection];
    
    // 数据解析
    [self dateHander];
    
    // 下拉刷新
    [self refresh];
    
    // 上拉加载 
    [self loading];
    
    
}

#pragma mark - 上拉加载
- (void)loading
{
    
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        //延迟两秒
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [LMTAFNetwork getUrl:[NSString stringWithFormat:@"http://apis.guokr.com/handpick/article.json?ad=1&category=all&retrieve_type=by_since&orientation=before&since=%@&limit=20",_model.date_picked] body:nil response:LMTJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
                
                NSArray *temp = resposeObject[@"result"];
                NSMutableArray *aTemp = [BoutiqueModel modelHanderWithArray:temp];
                for (BoutiqueModel *m in aTemp) {
                    [self.dataArr addObject:m];
                }
                [_collection reloadData];
                
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                
            }];
            [_collection.mj_footer endRefreshing];
        });
    }];
    _collection.mj_footer = footer;
}

#pragma mark - 下拉刷新
- (void)refresh
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
      
        //延迟2秒
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
                       dispatch_get_main_queue(),^{
                           
                           // 刷新
                           [self dateHander];
                           //新版本是 MJ_header
                           [self.collection.mj_header endRefreshing];
                       });
    }];
    self.collection.mj_header = header;
    header.stateLabel.font = [UIFont systemFontOfSize:12];
}

#pragma mark - 数据
- (void)dateHander
{
    NSString *str = @"http://apis.guokr.com/handpick/article.json?retrieve_type=by_since&ad=1&limit=20&category=all";
    [LMTAFNetwork getUrl:str body:nil response:LMTJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
       
        NSArray *arr = resposeObject[@"result"];
        self.dataArr = [BoutiqueModel modelHanderWithArray:arr];
        
        [_collection reloadData];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}



#pragma mark - 创建collectionView
- (void)creatCollection
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((self.view.frame.size.width - 30) / 2, 200 );
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.collection = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collection.backgroundColor = [UIColor whiteColor];
    
    
    _collection.delegate = self;
    _collection.dataSource = self;
    
    [_collection registerClass:[BoutiqueCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    [self.view addSubview:_collection];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    self.model = _dataArr.lastObject;
    return _dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    BoutiqueCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    BoutiqueModel *m = _dataArr[indexPath.item];
    
    [cell.img sd_setImageWithURL:[NSURL URLWithString:m.headline_img_tb]];
    cell.title.text = m.title;
    cell.fenlei.text = m.source_name;
    cell.time.text = [LMTTImeChuo boutiqueCurrentTime:m.date_picked];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    BoutiqueDetailController *bdVC = [[BoutiqueDetailController alloc] init];
    
    BoutiqueModel *m = _dataArr[indexPath.item];
    bdVC.str = m.link;
    
    [self.navigationController pushViewController:bdVC animated:YES];
    [bdVC release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
